package com.cinorecycle.printqrcode.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cinorecycle.printqrcode.common.PrintParam;
import com.cinorecycle.printqrcode.entity.result.ResultVo;
import com.cinorecycle.printqrcode.entity.vo.print.PrintVo;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * TODO
 *
 * @author ER GOU
 * @version 1.0
 * @date 2021/4/1 17:03
 */
@Slf4j
@Component
public class PrintUtils {

    @Autowired
    private RestTemplate restTemplate;

    private static String path = "./imgs";
    private static String url;

    static{
        String property = System.getProperty("user.dir");
        String p = property + "\\config.properties" ;

        Properties properties = new Properties();

        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(p));
            properties.load(bufferedReader);
        } catch (IOException e) {
            log.info(e.getMessage());
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                log.info(e.getMessage());
            }
        }

        url = properties.getProperty("host");
    }


    public PrintVo commonPrint(String deviceId) throws WriterException, IOException {
        PrintVo printVo = new PrintVo();

        File f = new File(path);
        if (!f.exists()) {
            f.mkdir();
        }

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map hints = new HashMap();
        //设置UTF-8， 防止中文乱码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //设置二维码四周白色区域的大小
        hints.put(EncodeHintType.MARGIN, 1);
        //设置二维码的容错性
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

        //width:图片完整的宽;height:图片完整的高
        //因为要在二维码下方附上文字，所以把图片设置为长方形（高大于宽）
        //int width = 500;//352
        //int height = 300;//612
        int width = PrintParam.areaWith;//352
        int height = PrintParam.areaHeight;//612
        //画二维码，记得调用multiFormatWriter.encode()时最后要带上hints参数，不然上面设置无效
        BitMatrix bitMatrix = multiFormatWriter.encode(deviceId + "", BarcodeFormat.QR_CODE, width, height, hints);

        //qrcFile用来存放生成的二维码图片（无logo，无文字）
        //File logoFile = new File(path, "logo.jpg");

        //开始画二维码
        BufferedImage barCodeImage = MatrixToImageWriter.writeToFile(bitMatrix, "jpg");

        //在二维码中加入图片
        //LogoConfig logoConfig = new LogoConfig(); //LogoConfig中设置Logo的属性
        //BufferedImage image = addLogo_QRCode(barCodeImage, logoFile, logoConfig);

        int font = 15; //字体大小
        int fontStyle = 1; //字体风格

        //用来存放带有logo+文字的二维码图片
        long t = System.currentTimeMillis();
        String newImageWithText = path + "/" + t + ".jpg";
        //附加在图片上的文字信息
        String getComputerVoInfoUrl = url + "/cinorecycle/all-in-one/id/" + deviceId;
        ResultVo resultVo = restTemplate.getForObject(getComputerVoInfoUrl, ResultVo.class);
        //String s1 = HttpUtil.get(getComputerVoInfoUrl);
        //ResultVo resultVo = JSON.parseObject(s1, ResultVo.class);

        String s = JSON.toJSONString(resultVo.getData(), SerializerFeature.WriteMapNullValue);

        printVo.setBufferedImage(barCodeImage)
                .setFont(font)
                .setFontStyle(fontStyle)
                .setString(s)
                .setNewImageWithText(newImageWithText)
        .setTime(t);
        return printVo;

    }

}
